package com.haoma.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.haoma.dto.CategoryDto;
import com.haoma.entity.PhotoCategory;
import com.haoma.entity.PhotoCategoryRelation;
import com.haoma.exception.BlogException;
import com.haoma.mapper.PhotoCategoryMapper;
import com.haoma.mapper.PhotoCategoryRelationMapper;
import com.haoma.minio.MinIOConfig;
import com.haoma.minio.MinIOConfigProperties;
import com.haoma.service.PhotoCategoryService;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Description:
 */
@Service
public class PhotoCategoryServiceImpl extends ServiceImpl<PhotoCategoryMapper, PhotoCategory> implements PhotoCategoryService {


    @Autowired
    private PhotoCategoryMapper photoCategoryMapper;

    @Autowired
    private PhotoCategoryRelationMapper photoCategoryRelationMapper;

    /**
     * 获取所有的分类
     *
     * @return
     */
    public List<PhotoCategory> getPhotoCategory() {
        List<PhotoCategory> list = list();
        return list;
    }

    @Autowired
    private MinIOConfig minIOConfig;

    @Autowired
    private MinIOConfigProperties minIOConfigProperties;

    /**
     * 分类封面上传
     *
     * @param multipartFile
     * @return
     */
    public String fileUpload(MultipartFile multipartFile) {
        try {
            // 连接客户端
            MinioClient minioClient = minIOConfig.buildMinioClient();
            // 判断桶是否存在
            boolean isBucket = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minIOConfigProperties.getBucket()).build());
            if (!isBucket) {
                // 不存在创建一个
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minIOConfigProperties.getBucket()).build());
            } else {
                // 提示程序员存在
                System.out.println("Bucket 'test' already exists.");
            }
            // 设置存储路径
            // 当天作为目录
            String date = DateUtil.format(new Date(), "yyyyMMdd");
            // 唯一id作为图片路径
            String uuid = UUID.randomUUID().toString().replace("-", "");
            // 组合＋业务
            String fileName = "admin-photo-category" + "/" + date + "/" + uuid + multipartFile.getOriginalFilename();
            System.out.println(fileName);

            // 构建上传参数
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(minIOConfigProperties.getBucket())
                    .stream(multipartFile.getInputStream(), multipartFile.getSize(), -1)
                    .object(fileName)
                    .build();
            // 上传
            minioClient.putObject(putObjectArgs);
            return minIOConfigProperties.getReadPath() + "/" + minIOConfigProperties.getBucket() + "/" + fileName;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 新增分类
     *
     * @param categoryDto
     */
    public void saveCategory(CategoryDto categoryDto) {
        PhotoCategory photoCategory = new PhotoCategory();
        BeanUtils.copyProperties(categoryDto, photoCategory);
        // 直接新增
        photoCategoryMapper.insert(photoCategory);
    }


    /**
     * 根据分类id删除分类
     *
     * @param id
     */
    public void delCategory(Integer id) {
        // 先查询
        LambdaQueryWrapper<PhotoCategory> photoCategoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        photoCategoryLambdaQueryWrapper.eq(PhotoCategory::getId, id);
        PhotoCategory photoCategory = photoCategoryMapper.selectOne(photoCategoryLambdaQueryWrapper);
        // 判断
        if (photoCategory == null) {
            throw new BlogException("删除失败");
        }
        // 可以删除了
        // 根据分类id查询第三方关系表中是否有
        LambdaQueryWrapper<PhotoCategoryRelation> photoCategoryRelationLambdaQueryWrapper = new LambdaQueryWrapper<>();
        photoCategoryRelationLambdaQueryWrapper.eq(PhotoCategoryRelation::getCategoryId, id);
        List<PhotoCategoryRelation> photoCategoryRelations = photoCategoryRelationMapper.selectList(photoCategoryRelationLambdaQueryWrapper);
        // 判断
        if (!CollectionUtils.isEmpty(photoCategoryRelations)) {
            throw new BlogException("该分类下还有照片不能删除");
        }
        // 可以删除
        photoCategoryMapper.delete(photoCategoryLambdaQueryWrapper);
    }


    /**
     * 修改相册分类
     *
     * @param id
     * @param categoryDto
     */
    public void updateCategory(Integer id, CategoryDto categoryDto) {
        // 先查询
        LambdaQueryWrapper<PhotoCategory> photoCategoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        photoCategoryLambdaQueryWrapper.eq(PhotoCategory::getId, id);
        PhotoCategory photoCategory = photoCategoryMapper.selectOne(photoCategoryLambdaQueryWrapper);
        // 判断
        if (photoCategory == null) {
            throw new BlogException("修改失败");
        }
        // 可以修改
        PhotoCategory photoCategoryEntity = new PhotoCategory();
        BeanUtils.copyProperties(categoryDto, photoCategoryEntity);
        photoCategoryEntity.setId(id);
        photoCategoryMapper.updateById(photoCategoryEntity);
    }

    /**
     * 根据id回显相册
     *
     * @param id
     * @return
     */
    public PhotoCategory getCategory(Integer id) {
        LambdaQueryWrapper<PhotoCategory> photoCategoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        photoCategoryLambdaQueryWrapper.eq(PhotoCategory::getId, id);
        PhotoCategory photoCategory = photoCategoryMapper.selectOne(photoCategoryLambdaQueryWrapper);
        if (photoCategory == null) {
            throw new BlogException("回显失败");
        }
        return photoCategory;
    }
}
